package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
public class CommonController {
    @Resource
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        try {
            // 获取文件的原始名称
            String originalFileName = file.getOriginalFilename();
            // 截取原始文件名的后缀：从最后一个.截取到最后
            String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
            // 新的文件名
            String name = UUID.randomUUID().toString() + extension;
            // 上传成功后的文件地址
            String filePath = aliOssUtil.upload(file.getBytes(), name);

            return Result.success(filePath);
        } catch (Exception e) {
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }
}
